import dayjs from 'dayjs'

// 格式化日期
export const formatDate = (date, format = 'YYYY-MM-DD') => {
  return dayjs(date).format(format)
}

// 格式化日期时间
export const formatDateTime = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  return dayjs(date).format(format)
}

// 获取相对时间
export const getRelativeTime = (date) => {
  const now = dayjs()
  const target = dayjs(date)
  const diff = now.diff(target, 'day')
  
  if (diff === 0) {
    return '今天'
  } else if (diff === 1) {
    return '昨天'
  } else if (diff === 2) {
    return '前天'
  } else if (diff < 7) {
    return `${diff}天前`
  } else {
    return target.format('MM-DD')
  }
}

// 防抖函数
export const debounce = (func, wait) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 节流函数
export const throttle = (func, limit) => {
  let inThrottle
  return function() {
    const args = arguments
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 生成随机ID
export const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 深拷贝
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (obj instanceof Object) {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

// 获取文件扩展名
export const getFileExtension = (filename) => {
  return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2)
}

// 格式化文件大小
export const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 验证邮箱
export const isValidEmail = (email) => {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return re.test(email)
}

// 验证手机号
export const isValidPhone = (phone) => {
  const re = /^1[3-9]\d{9}$/
  return re.test(phone)
}

// 获取当前平台
export const getPlatform = () => {
  // #ifdef H5
  return 'h5'
  // #endif
  
  // #ifdef MP-WEIXIN
  return 'mp-weixin'
  // #endif
  
  // #ifdef MP-ALIPAY
  return 'mp-alipay'
  // #endif
  
  // #ifdef APP-PLUS
  return 'app'
  // #endif
  
  return 'unknown'
}

// 页面跳转封装
export const navigateTo = (url, params = {}) => {
  let fullUrl = url
  if (Object.keys(params).length > 0) {
    const query = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&')
    fullUrl += `?${query}`
  }
  
  uni.navigateTo({
    url: fullUrl,
    fail: (err) => {
      console.error('页面跳转失败:', err)
    }
  })
}

// 返回上一页
export const navigateBack = (delta = 1) => {
  uni.navigateBack({
    delta
  })
}

/**
 * 提取API响应中的数据
 * 兼容两种格式：
 * 1. 包装格式: {code: 200, message: "success", data: {...}}
 * 2. 直接格式: {message: "success", data: {...}, user: {...}}
 */
export function extractResponseData(response) {
  // 如果响应有data字段，优先使用data字段的值
  if (response.data !== undefined) {
    return response.data
  }
  
  // 否则返回整个响应对象（去除一些元数据字段）
  const { code, statusCode, ...data } = response
  return data
}

/**
 * 检查API响应是否成功
 * 兼容不同的响应格式
 */
export function isResponseSuccess(response) {
  // 包装格式：检查code字段
  if (response.code !== undefined) {
    return response.code === 200
  }
  
  // 直接格式：检查是否有message字段或token字段（一般成功响应会有）
  return response.message || response.token || response.user
} 